package api.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FunctionUtils {

    private static final String regx_function="#\\{(.*?)\\}";
    private static final Pattern pattern_function=Pattern.compile(regx_function);

    private static final String regx_parmas="\\((.*?)\\)";
    private static final Pattern pattern_parmas=Pattern.compile(regx_parmas);

    private static final Base64 base64 = new Base64();

    //token=#{md5(abc,abc)};userId=#{base64(test,abc)}
    public static String  function(String str){
        if(StringUtils.isNotBlank(str)){
            Matcher matcher = pattern_function.matcher(str);
            while (matcher.find()) {
                String function_regx = matcher.group();
                String function = matcher.group(1);
                if(function.startsWith("md5")){
                    String parmas=getParmas(function);
                    String md5Hex = DigestUtils.md5Hex(parmas.getBytes(StandardCharsets.UTF_8));
                    str=str.replace(function_regx,md5Hex);
                }else if (function.startsWith("base64")){
                    String parmas=getParmas(function);
                    String base64Str = base64.encodeToString(parmas.getBytes(StandardCharsets.UTF_8));
                    str=str.replace(function_regx,base64Str);
                }else if (function.equals("time")){
                    str=str.replace(function_regx,""+System.currentTimeMillis());
                }else if (function.equals("uuid")){
                    str=str.replace(function_regx,""+ UUID.randomUUID());
                }
            }
        }
        return str;
    }

    //md5(abc,abc)
    private static String getParmas(String function) {
        Matcher matcher = pattern_parmas.matcher(function);
        if (matcher.find()){
            // System.out.println(matcher.group()+" --- "+matcher.group(1));
            return matcher.group(1).replace(",", "");
        }
        return "";
    }

    public static void main(String[] args) {
        String token="token=#{md5(${loginname},${loginpass})};userId=#{base64(${loginname},${loginpass})};t=#{time}";
        //String token="token=base64(${loginname},${loginpass})";
        HashMap<String, Object> map = new HashMap<>();
        map.put("loginname","abc");
        map.put("loginpass","test");

        String newStr = ParamsUtils.replace(token, map);

      //  System.out.println(FunctionUtils.function(newStr));


    }
}
